import json

from django.conf import settings
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models


class TencentSms:
    def __init__(self):
        self.cred = credential.Credential(settings.SMS_SECRET_ID, settings.SMS_SECRET_KEY)
        self.SmsSdkAppId = settings.SMS_APPID

    def send(self, phone, code):
        try:
            httpProfile = HttpProfile()
            httpProfile.endpoint = "sms.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = sms_client.SmsClient(self.cred, "ap-beijing", clientProfile)

            req = models.SendSmsRequest()
            params = {
                "PhoneNumberSet": ["+86{}".format(phone.strip())],
                "SmsSdkAppId": self.SmsSdkAppId,
                "SignName": "志愿吧",
                "TemplateId": "1152096",
                "TemplateParamSet": [str(code), "10"]
            }
            req.from_json_string(json.dumps(params))

            resp = client.SendSms(req)
            return resp.to_json_string()

        except TencentCloudSDKException as err:
            print(err)
